package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;

import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 *  金通宝双授权
 */
@Service
public class JinTongBaoApiSService implements IPushApiService, IPushApi2Service {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;



    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String orderNum = UUID.randomUUID().toString();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobileMd5",memberSourceInfo.getMobileMd5());
        bizMap.put("realname",memberSourceInfo.getRealname());
        bizMap.put("sex",memberSourceInfo.getSex());
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("idCard",memberSourceInfo.getIdcard());
        bizMap.put("province",memberSourceInfo.getProvince());
        bizMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        bizMap.put("city",memberSourceInfo.getCity());
        bizMap.put("cityCode",memberSourceInfo.getCityCode());
        bizMap.put("loanAmount",memberSourceInfo.getLoanAmount());
        bizMap.put("huabei",memberSourceInfo.getHuabei());
        bizMap.put("shebao",memberSourceInfo.getShebao());
        bizMap.put("baitiao",memberSourceInfo.getBaitiao());
        bizMap.put("yuqi",memberSourceInfo.getYuqi());
        bizMap.put("house",memberSourceInfo.getHouse());
        bizMap.put("loanTime",memberSourceInfo.getLoanTime());
        bizMap.put("baoxian",memberSourceInfo.getBaoxian());
        bizMap.put("car",memberSourceInfo.getCar());
        bizMap.put("xueli",memberSourceInfo.getXueli());
        bizMap.put("shouru",memberSourceInfo.getShouru());
        bizMap.put("gongzuo",memberSourceInfo.getGongzuo());
        bizMap.put("yongtu",memberSourceInfo.getYongtu());
        bizMap.put("weili",memberSourceInfo.getWeili());
        bizMap.put("xinyongka",memberSourceInfo.getXinyongka());
        bizMap.put("gjj",memberSourceInfo.getGjj());
        bizMap.put("zhima",memberSourceInfo.getZhima());
        bizMap.put("ip",memberSourceInfo.getReqIp());
        String data = SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(bizMap));
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("data",data);
        String appId = pushApiKeyParam.getApiCode();
        long timestamp = System.currentTimeMillis();
        SortedMap<String, String> headerMap = new TreeMap<>();
        headerMap.put("appId", appId);
        headerMap.put("timestamp", String.valueOf(timestamp));
        headerMap.put("nonce", orderNum);

        StringBuilder signatureBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            if (signatureBuilder.length() > 0) {
                signatureBuilder.append("&");
            }
            signatureBuilder.append(entry.getKey()).append("=").append(entry.getValue());
        }
        String signature = signatureBuilder+pushApiKeyParam.getApiSecret(); // 最终拼接的字符串
        // 计算 SHA-256 签名
        String sign = DigestUtil.sha256Hex(JSON.toJSONString(paramMap)+signature);
        headerMap.put("sign", sign);
        log.info("【金通宝】撞库开始【queryUrl】{}【paramMap】{}【headerMap】{}【bizMap】{}【signature】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(headerMap), JSON.toJSONString(bizMap), signature);
        String result = HttpUtil.createPost(queryUrl)
                .headerMap(headerMap, true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【金通宝】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);

        int code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (code == 0) {
            JSONObject data1 = resultObject.getJSONObject("data");
            String logo = data1.getString("logo");
            String name = data1.getString("name");
            String orderId = data1.getString("orderId");
            String orgName = data1.getString("orgName");
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo", orderNum);
            infoObject.put("productId", orderNum);
            infoObject.put("productName", name);
            infoObject.put("companyName", orgName);
            infoObject.put("companyLogo", logo);
            infoObject.put("maxLoanAmount", "200000");
            infoObject.put("maxLoanRate", "20");
            infoObject.put("minLoanRate", "1");
            infoObject.put("businessInfo", name);
            JSONArray jsonArray = new JSONArray();
            JSONArray authAgree = data1.getJSONArray("protocols");
            for (int i = 0; i < authAgree.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                JSONObject jsonObject1 = authAgree.getJSONObject(i);
                String name1 = jsonObject1.getString("label");
                String url = jsonObject1.getString("value");
                jsonObject.put("protocalName", name1);
                jsonObject.put("protocalUrl", url);
                jsonArray.add(jsonObject);
            }
            infoObject.put("protocalList", jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);
            JSONArray md5List = data1.getJSONArray("mobilesMd5");
            String mobileMd5 = memberSourceInfo.getMobileMd5();
            if(MobileMd5IsInListUtils.isMobileMd5InList(md5List,mobileMd5)) {
                //如果存在
                pushApiResult.setPushSuccess(false);
                pushApiResult.setCode(code + "|" + "500");
                pushApiResult.setMessage(msg + "|" + mobileMd5 + "已存在");
                return pushApiResult;
            }
            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save) {
                pushApiResult.setPushSuccess(true);
                pushApiResult.setOutOrderNo(orderNum);
                extJson.put("orderIds", orderId);
            } else {
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String orderId = extJson.getString("orderIds");
        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobile",memberSourceInfo.getMobile());
        bizMap.put("realname",memberSourceInfo.getRealname());
        bizMap.put("sex",memberSourceInfo.getSex());
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("idCard",memberSourceInfo.getIdcard());
        bizMap.put("province",memberSourceInfo.getProvince());
        bizMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        bizMap.put("city",memberSourceInfo.getCity());
        bizMap.put("cityCode",memberSourceInfo.getCityCode());
        bizMap.put("loanAmount",memberSourceInfo.getLoanAmount());
        bizMap.put("huabei",memberSourceInfo.getHuabei());
        bizMap.put("shebao",memberSourceInfo.getShebao());
        bizMap.put("baitiao",memberSourceInfo.getBaitiao());
        bizMap.put("yuqi",memberSourceInfo.getYuqi());
        bizMap.put("house",memberSourceInfo.getHouse());
        bizMap.put("loanTime",memberSourceInfo.getLoanTime());
        bizMap.put("baoxian",memberSourceInfo.getBaoxian());
        bizMap.put("car",memberSourceInfo.getCar());
        bizMap.put("xueli",memberSourceInfo.getXueli());
        bizMap.put("shouru",memberSourceInfo.getShouru());
        bizMap.put("gongzuo",memberSourceInfo.getGongzuo());
        bizMap.put("yongtu",memberSourceInfo.getYongtu());
        bizMap.put("weili",memberSourceInfo.getWeili());
        bizMap.put("xinyongka",memberSourceInfo.getXinyongka());
        bizMap.put("gjj",memberSourceInfo.getGjj());
        bizMap.put("zhima",memberSourceInfo.getZhima());
        bizMap.put("ip",memberSourceInfo.getReqIp());

        String data = SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("data",data);
        paramMap.put("orderId",orderId);
        long timestamp = System.currentTimeMillis();
        String orderNum = UUID.randomUUID().toString();
        String appId = pushApiKeyParam.getApiCode();
        SortedMap<String, String> headerMap = new TreeMap<>();
        headerMap.put("appId", appId);
        headerMap.put("timestamp", String.valueOf(timestamp));
        headerMap.put("nonce", orderNum);

        StringBuilder signatureBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            if (signatureBuilder.length() > 0) {
                signatureBuilder.append("&");
            }
            signatureBuilder.append(entry.getKey()).append("=").append(entry.getValue());
        }
        String signature = signatureBuilder+pushApiKeyParam.getApiSecret(); // 最终拼接的字符串
        String sign = DigestUtil.sha256Hex(JSON.toJSONString(paramMap)+signature);
        headerMap.put("sign", sign);

        log.info("【金通宝】导单开始【requestUrl】{}【paramMap】{}【headerMap】{}【bizMap】{}【signature】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(headerMap), JSON.toJSONString(bizMap), signature);
        String result = HttpUtil.createPost(requestUrl)
                .headerMap(headerMap, true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【金通宝】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);

        int code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(code + "");
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 0) {
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 0) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String orderNum = UUID.randomUUID().toString();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobileMd5",memberSourceInfo.getMobileMd5());
        bizMap.put("realname",memberSourceInfo.getRealname());
        bizMap.put("sex",memberSourceInfo.getSex());
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("idCard",memberSourceInfo.getIdcard());
        bizMap.put("province",memberSourceInfo.getProvince());
        bizMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        bizMap.put("city",memberSourceInfo.getCity());
        bizMap.put("cityCode",memberSourceInfo.getCityCode());
        bizMap.put("loanAmount",memberSourceInfo.getLoanAmount());
        bizMap.put("huabei",memberSourceInfo.getHuabei());
        bizMap.put("shebao",memberSourceInfo.getShebao());
        bizMap.put("baitiao",memberSourceInfo.getBaitiao());
        bizMap.put("yuqi",memberSourceInfo.getYuqi());
        bizMap.put("house",memberSourceInfo.getHouse());
        bizMap.put("loanTime",memberSourceInfo.getLoanTime());
        bizMap.put("baoxian",memberSourceInfo.getBaoxian());
        bizMap.put("car",memberSourceInfo.getCar());
        bizMap.put("xueli",memberSourceInfo.getXueli());
        bizMap.put("shouru",memberSourceInfo.getShouru());
        bizMap.put("gongzuo",memberSourceInfo.getGongzuo());
        bizMap.put("yongtu",memberSourceInfo.getYongtu());
        bizMap.put("weili",memberSourceInfo.getWeili());
        bizMap.put("xinyongka",memberSourceInfo.getXinyongka());
        bizMap.put("gjj",memberSourceInfo.getGjj());
        bizMap.put("zhima",memberSourceInfo.getZhima());
        bizMap.put("ip",memberSourceInfo.getReqIp());
        String data = SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(bizMap));
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("data",data);
        String appId = pushApiKeyParam.getApiCode();
        long timestamp = System.currentTimeMillis();
        SortedMap<String, String> headerMap = new TreeMap<>();
        headerMap.put("appId", appId);
        headerMap.put("timestamp", String.valueOf(timestamp));
        headerMap.put("nonce", orderNum);

        StringBuilder signatureBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            if (signatureBuilder.length() > 0) {
                signatureBuilder.append("&");
            }
            signatureBuilder.append(entry.getKey()).append("=").append(entry.getValue());
        }
        String signature = signatureBuilder+pushApiKeyParam.getApiSecret(); // 最终拼接的字符串
        // 计算 SHA-256 签名
        String sign = DigestUtil.sha256Hex(JSON.toJSONString(paramMap)+signature);
        headerMap.put("sign", sign);
        log.info("【上游金通宝】撞库开始【queryUrl】{}【paramMap】{}【headerMap】{}【bizMap】{}【signature】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(headerMap), JSON.toJSONString(bizMap), signature);
        String result = HttpUtil.createPost(queryUrl)
                .headerMap(headerMap, true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【上游金通宝】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);

        int code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (code == 0) {
            JSONObject data1 = resultObject.getJSONObject("data");
            String logo = data1.getString("logo");
            String name = data1.getString("name");
            String orderId = data1.getString("orderId");
            String orgName = data1.getString("orgName");
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo", orderNum);
            infoObject.put("productId", orderNum);
            infoObject.put("productName", name);
            infoObject.put("companyName", orgName);
            infoObject.put("companyLogo", logo);
            infoObject.put("maxLoanAmount", "200000");
            infoObject.put("maxLoanRate", "20");
            infoObject.put("minLoanRate", "1");
            infoObject.put("businessInfo", name);
            JSONArray jsonArray = new JSONArray();
            JSONArray authAgree = data1.getJSONArray("protocols");
            for (int i = 0; i < authAgree.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                JSONObject jsonObject1 = authAgree.getJSONObject(i);
                String name1 = jsonObject1.getString("label");
                String url = jsonObject1.getString("value");
                jsonObject.put("protocalName", name1);
                jsonObject.put("protocalUrl", url);
                jsonArray.add(jsonObject);
            }
            infoObject.put("protocalList", jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);
            JSONArray md5List = data1.getJSONArray("mobilesMd5");
            pushApiResult.setMd5List(md5List);
            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save) {
                pushApiResult.setPushSuccess(true);
                pushApiResult.setOutOrderNo(orderNum);
                extJson.put("orderIds", orderId);
            } else {
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }
}
